import {ComponentInternalInstance} from 'vue'
import {useIFrameOrigin} from "@/views/workTable/compositions/useSrc";


export interface IFrameRequestBody {
  method: string,
  args: any,
}

export default function useIFrameRequest() {
  const origin = useIFrameOrigin()

  // 主动调用parent方法
  const iframeRequest = (requestBody: IFrameRequestBody) => {
    return new Promise(resolve => {
      const handleResponse = (e: MessageEvent) => {
        resolve(e.data)
        window.removeEventListener('message', handleResponse)
      }

      window.addEventListener('message', handleResponse)
      parent.postMessage(requestBody, origin)
    })
  }

  let vmCtx: ComponentInternalInstance
  const iframeListener = (context: ComponentInternalInstance) => {
    if (self !== top) {
      vmCtx = context
      window.addEventListener('message', iframeListenHandler)
      parent.postMessage({method: 'worktableReady'}, origin)
    }
  }

  const iframeListenHandler = (e: MessageEvent) => {
    // console.log('merchant => iframeListenHandler => message received', e)
    const {method, args} = e.data
    vmCtx[method](args)
  }

  onBeforeUnmount(() => {
    window.removeEventListener('message', iframeListenHandler)
  })

  return {
    iframeRequest,
    iframeListener
  }
}
